var LOADING = '数据加载中';
var EMPTY = '选择条件内无数据';
//var timeInterval = setInterval("$('#now').text(getDate(new Date()).datetime());", 1000);
if (['/forgetPassword.html', '/regist.html', '/pages/changePhone.html', '/pages/home', '/pages/home.html'].indexOf(top.location.pathname) < 0){
    top.location.href = 'home.html?token=' + sessionStorage.getItem('token');
}

$(function () {
    userInfo();
    //获取当前加载子页面，给其相应菜单栏加高亮
    switch (location.pathname) {
        case '/pages/index.html':
            $('.nav-menu a', window.parent.document).eq(0).addClass('active').siblings().removeClass('active');
            break;
        case '/pages/deviceList.html':
            $('.nav-menu a', window.parent.document).eq(1).addClass('active').siblings().removeClass('active');
            break;
        case '/pages/alarmDay.html':
        case '/pages/alarmHistory.html':
            $('.nav-menu a', window.parent.document).eq(2).addClass('active').siblings().removeClass('active');
            break;
        case '/pages/reports.html':
            $('.nav-menu a', window.parent.document).eq(3).addClass('active').siblings().removeClass('active');
            break;
        case '/pages/prdEquMaintenance.html':
            $('.nav-menu a', window.parent.document).eq(4).addClass('active').siblings().removeClass('active');
            break;
        default:
            $('.nav-menu a', window.parent.document).removeClass('active');
            break;
    }
});

function userInfo() {
    if ($('#userInfo').length > 0) {
        getJson('/sys/userInfo', null, 'GET', function (data) {
            $('#userInfo').text('欢迎您，' + data['payload']['data']['displayName']);
        })
    }
}

/*生成随机数组*/
function randomFun(count, baseNum, diffNum, decimal) {//count数组长度, baseNum基础值, diffNum浮动值，decimal保留几位小数，
    var data = [];
    for (var i = 0; i < count; i++) {
        data[i] = (Math.random() * diffNum + baseNum).toFixed(decimal);
    }
    return data;
}

function increaseArr(count, begin) {//count长度,begin起始值
    var data = [];
    for (var i = 0; i < count; i++) {
        data[i] = '6-' + (i + begin);
    }
    return data;
}

function TimeNow() {
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var date = myDate.getDate();
    var hour = myDate.getHours();
    var minute = myDate.getMinutes();
    var second = myDate.getSeconds();

    var now = [year, month, date].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
    return now;
}

/* 获取格式的时间，返回3个字段的对象类型   update 可传参，参数为date对象*/
function getFormatTime(dateObj) {
    var myDate;
    if (dateObj) {
        myDate = dateObj;
    } else {
        myDate = new Date();
    }
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var date = myDate.getDate();
    var hour = myDate.getHours();
    var minute = myDate.getMinutes();
    var second = myDate.getSeconds();

    var week_arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    var week = week_arr[myDate.getDay()];

    return {
        formatDate: [year, month, date].map(formatNumber).join('-'), //YYYY-MM-DD
        formatTime: [hour, minute, second].map(formatNumber).join(':'), //HH:MM:SS
        week: week
    };
}

function TimeNowUnsign() {
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var date = myDate.getDate();
    var hour = myDate.getHours();
    var minute = myDate.getMinutes();
    var second = myDate.getSeconds();
    var now = [year, month, date].map(formatNumber).join('') + [hour, minute, second].map(formatNumber).join('');
    return now;
}


//递增时间数组，由当日0点开始到当前时间，15min一条
function increaseTime() {
    var curTime = new Date();//当前
    var curStamp = +curTime;
    var zero = new Date(curTime.getFullYear(), curTime.getMonth(), curTime.getDate());//今日零点
    var zeroStamp = +zero;
    var space = 15 * 60 * 1000;
    var timeArr = [];
    timeArr.push([formatNumber(zero.getHours()), formatNumber(zero.getMinutes())].join(':'));
    for (; zeroStamp < curStamp; zeroStamp += space) {
        var zero = new Date(zeroStamp);
        timeArr.push([formatNumber(zero.getHours()), formatNumber(zero.getMinutes())].join(':'));
    }
    return timeArr;
}

//日期时间处理
function formatNumber(s) {
    return s < 10 ? '0' + s : s;
}

/*截取地址栏参数*/
function getQueryString(name) {
    var result = decodeURI(window.location.search).match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[1];
}

/* 点缩略图查看大图 */
//需配合模态弹窗viewImageModal服用
$('body').delegate('.img-preview', 'click', function () {
    showImpLoading('加载中');
    var url = $(this).prop('src');
    var url_origin = $(this).attr('data-origin');
    if (!isNull(url_origin)) {
        url = url_origin;
    }
    $('#img_preview_area').prop('src', url);
    $('#img_preview_area')[0].onload = function () {
        $('#viewImageModal').modal();
        hideLoading();
    }
    $('#img_preview_area')[0].onerror = function () {
        $('#img_preview_area').prop('src', '../customize/images/no-photo.png');
        $('#viewImageModal').modal();
        hideLoading();
    }
})

// /* 下载页面某部分内容为pdf */
// function downloadPDF_t(domId, fileName){
//   html2canvas(document.getElementById(domId), {
//     onrendered:function(canvas) {
//       //返回图片dataURL，参数：图片格式和清晰度(0-1)
//       var pageData = canvas.toDataURL('image/jpeg', 1.0);
//       //方向默认竖直，尺寸ponits，格式a4[595.28,841.89]
//       var pdf = new jsPDF('', 'pt', 'a4');
//       //addImage后两个参数控制添加图片的尺寸，此处将页面高度按照a4纸宽高比列进行压缩
//       pdf.addImage(pageData, 'JPEG', 0, 0, 595.28, 592.28/canvas.width * canvas.height );
//       pdf.save(fileName + '.pdf');
//     }
//   })
// }
/* 下载页面某部分内容为jpg格式图片 */
function downloadIMG_t(domId, fileName) {
    html2canvas(document.getElementById(domId), {
        onrendered: function (canvas) {
            //返回图片dataURL，参数：图片格式和清晰度(0-1)
            var pageData = canvas.toDataURL('image/jpeg', 1.0);
            var oA = document.createElement("a");
            oA.download = fileName;// 设置下载的文件名，默认是'下载'
            oA.href = pageData;
            document.body.appendChild(oA);
            oA.click();
            oA.remove(); // 下载之后把创建的元素删除
        }
    })
}

// 设置显示的行
function set_tr(e) {
    var start = (e - 1) * 10 + 1;
    var end = e * 10;
    $('#exportExcel tbody tr').addClass('d-none');
    for (var i = start; i <= end; i++) { // tr_len是要控制的tr个数
        $("#tr_" + i).removeClass('d-none');
    }
}

function sendMsg(e, phone, interval) {
    // var regular = /^((\+|00)86)?((134\d{4})|((13[0-3|5-9]|14[1|5-9]|15[0-9]|16[2|5|6|7]|17[0-8]|18[0-9]|19[0-2|5-9])\d{8}))$/;
    var regular = /^1[0-9]{10}$/;
    if (!regular.test(phone)) {
        showModalHint("none", "请输入正确的手机号");
        return;
    }
    $(e).css('pointerEvents', 'none');
    if (!phone) {
        $(e).css('pointerEvents', 'auto');
        return;
    }
    showModalHint('success', '验证码已发送，五分钟内有效');
    getJson('/sys/sendMsg', {
        username: phone
    }, 'GET', function () {
        var time = 60;
        if (interval) {
            clearInterval(interval);
        }
        interval = setInterval(function () {
            time--;
            $(e).text('重新发送 ' + time + 's');
            if (time <= 0) {
                clearInterval(interval);
                $(e).text('发送验证码');
                $(e).css('pointerEvents', 'auto');
            }
        }, 1000);
    })
}

function setPaging_simple(pageElement, index, totalPage, totalSize, callback) {
    $(pageElement).paging_simple({//稼动率弹窗中的分页初始化
        pageNo: index,
        totalPage: totalPage,
        totalSize: totalSize,
        callback: function (num) {
            if (callback) {
                callback(num)
            }
        }
    })
}

function setPage(pageElement, index, totalPage, totalSize, callback) {
    $(pageElement).paging({
        pageNo: index,
        totalPage: totalPage,
        totalSize: totalSize,
        callback: function (num) {
            if (callback) {
                callback(num)
            }
        }
    });
}

function setPageSimple(pageElement, index, totalPage, totalSize, callback) {
    $(pageElement).paging_simple({//稼动率弹窗中的分页初始化
        pageNo: index,
        totalPage: totalPage,
        totalSize: totalSize,
        callback: function (num) {
            if (callback) {
                callback(num)
            }
        }
    })
}

// $(function () {
//   itemsResize();
// });

// /* 监测窗口大小改变 */
// var resizeWaiter = false;
// $(window).resize(function () {
//   if (!resizeWaiter) {
//     resizeWaiter = true;
//     setTimeout(function () {
//       itemsResize();
//       resizeWaiter = false;
//     }, 500);
//   }
// });
/* 根据窗口大小缩放、调整位置  缩放body方法，modal随之缩放 */
//modal缩放但需调遮罩层大小单位由vw变为%；laydate缩放但位置跑偏（它使用像素定位的）
//两种方法的canvas导出都有异常
// function itemsResize() {
//   var body_width = document.documentElement.clientWidth;//获取页面可见宽度
//   var body_height = $('.main').outerHeight() + 29;//获取页面可见高度
//   var scale = body_width / 1920;

//   $('body').css({
//     width: '1920px',
//     height: body_height * scale,
//     transform: 'scale(' + scale + ')',
//     transformOrigin: 'left top',
//     backgroundSize: "100% 100%",
//   });
//}

// /* 根据窗口大小缩放、调整位置  缩放.main方法 */
// //modal、laydate弹窗都不缩放
// function itemsResize() {
//   var body_width = document.documentElement.clientWidth;//获取页面可见宽度
//   var scale = body_width / 1920;
//   var oright_height = $('.main').outerHeight() * scale ;//缩放后的容器实际高度

//   $('.main').removeClass('mx-auto').css({
//     transform: 'scale(' + scale + ')',
//     transformOrigin: 'center top 0px',
//     marginLeft: (scale * 1877 - 1877) / 2 + (body_width - scale * 1877) / 2 + 'px',
//     height: oright_height
//   });
// }

//四舍五入保留2位小数（不够位数，则用0替补）
function keepTwoDecimalFull(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
        alert('传递参数错误，请检查！');
        return false;
    }
    result = Math.round(num * 100) / 100;
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    return s_x;
}

/*将小数转换为百分比*/
function toPercent(point) {
    if (point == 0) {
        return 0;
    }
    var str = Math.round(Number(point * 100) * 100 / 100);
    str += "%";
    return str;
}

function current() {
    var d = new Date(), str = '';
    str += d.getFullYear() + '-'; //获取当前年份
    str += d.getMonth() + 1 + '-'; //获取当前月份（0——11）
    str += d.getDate() + ' ';
    str += d.getHours() + ':';
    str += d.getMinutes() + ':';
    str += d.getSeconds();
    return str;
}

function judgeThePeakValleyFlat(time) {
    time = time.toString();
    if (Number(time.substr(0, 2)) >= 0 && Number(time.substr(0, 2)) < 8) {//谷
        return 'min';
    } else if ((Number(time.substr(0, 2)) >= 12 && Number(time.substr(0, 2)) < 17) || (Number(time.substr(11, 2)) >= 21)) {
        return 'avg';
    } else {
        return 'max';
    }
}

/*加载企业信息*/
function loadEnterprise() {
    getJson('/company/getCompanyById', null, 'GET', function (result) {
        sessionStorage.setItem("company_name", result.name);
        $('#company_name').html(result.name);
        $('#address_id').html(result.province + result.city + result.address);
        $('#logo_img').attr('src', fileUrl + result.logo);
        $('#photo_img').attr('src', fileUrl + result.photo);
    })
}

/*判断开始时间和结束时间的差不超过30天*/
function oneMonthLimit(beginDate, endDate) {
    if (!beginDate && !endDate) {
        return;
    }
    var bDate = new Date(beginDate);
    var eDate = new Date(endDate);
    var difference = eDate.getTime() / (1000 * 60 * 60 * 24) - bDate.getTime() / (1000 * 60 * 60 * 24)
    return difference > 30;
}

/*判断开始时间和结束时间的差不超过7天*/
function oneWeekhLimit(beginDate, endDate) {
    if (!beginDate && !endDate) {
        return;
    }
    var bDate = new Date(beginDate);
    var eDate = new Date(endDate);
    var difference = eDate.getTime() / (1000 * 60 * 60 * 24) - bDate.getTime() / (1000 * 60 * 60 * 24)
    return difference > 7;
}

/*判断开始时间和结束时间的差不超过7天（最大值6天）*/
function oneWeekLimit(beginDate, endDate) {
    if (!beginDate && !endDate) {
        return;
    }
    var bDate = new Date(beginDate);
    var eDate = new Date(endDate);
    var difference = (eDate - bDate) / (1000 * 60 * 60 * 24);
    return difference >= 7;
}

/*
        压缩图片，压缩后的图片为jpg格式
        file：获取到的图片文件
        max_width、max_height：压缩后的宽、高的最大值
        encoderOptions：图片质量，在指定图片格式为 image/jpeg 或 image/webp的情况下，可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围，将会使用默认值 0.92。
        callBack：压缩完成的回调函数，传参：压缩后的blob文件
    */
function compressPicture(file, max_width, max_height, encoderOptions, callBack) {
    var reader = new FileReader();
    if (!isNull(file)) {
        reader.readAsDataURL(file);
        reader.onload = function () {
            var img_base64 = reader.result;
            var img = new Image();
            img.src = img_base64;
            img.onload = function () {
                var image_width = max_width,
                    image_height = max_height;
                if (img.width < max_width && img.height < max_height) {//图片宽高均小于压缩值，使用原图尺寸
                    image_width = img.width;
                    image_height = img.height;
                } else {
                    //判断是横图还是竖图
                    if (img.width / img.height >= 1) {//横图或者正方形图
                        if (img.width >= max_width) {
                            image_width = max_width;
                            image_height = Math.round(img.height / (img.width / max_width));
                        }
                    } else {//竖图
                        if (img.height >= max_height) {
                            image_width = Math.round(img.width / (img.height / max_height));
                            image_height = max_height;
                        }
                    }
                }
                //新建canvas元素，用来对图片进行压缩
                var canvas = document.createElement("canvas");
                canvas.width = image_width;
                canvas.height = image_height;
                var context = canvas.getContext("2d");
                context.drawImage(img, 0, 0, image_width, image_height);
                var res_blob = canvas.toBlob(function (blob) {
                    if (callBack) {
                        callBack(blob);
                    }
                }, "image/jpeg", encoderOptions);//转化为Blob文件
            }
        }
    } else {
        callBack(null);
    }
}

/*由原图路径拼接缩略图路径*/
function concatMinImgUrl(url) {
    if (!isNull(url)) {
        return url.replace('/', '/min');
    } else {
        return url;
    }
}

/*前进后退更新当前页的cookie*/
$(function () {
    if (window.performance.navigation.type == 2) {//前进或后退按钮加载
        var pathname = location.pathname;
        var url = pathname.replace('/pages/', '');
        if (pathname == '/pages/deviceData.html') {//设备数据页带参数
            url = url + location.search;
        }
        if (url == 'index.html' || url == 'deviceList.html' || url == 'prdEquManagement.html' || url == 'gridReport.html' || url == 'elecPwrReport.html'
            || url == 'prdEquMaintenance.html' || url == 'userInfo.html' || url.indexOf('deviceData.html') > -1) {
            $.cookie('mainIframeUrlCookie', url, {path: '/'});
        }
    }
})

function loadDeviceType(select) {
    getJson("/deviceType/getAllByUser", null, 'GET', function (result) {
        buildSelectNoData($(select), result['payload']['data'], 'title', 'id', '选择设备类型');
    })
}

function contrastTime(toDay, time) {
    var toDayTimestamp = new Date(toDay).valueOf();
    var timestamp = new Date(time).valueOf();
    return toDayTimestamp > timestamp
}